package com.android.BluethootChess.ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.widget.ImageView;

import com.android.BluethootChess.control.TouchController;
import com.android.BluethootChess.model.GameBoardMatrix;
import com.android.BluethootChess.util.Utils;

/**
 * Creaza o tabla de sah.
 */
public class ChessBoard extends ImageView {

	private int boardColors[];
	private Bitmap bitmapImage;
	private UISquares squares;
	

	public ChessBoard(Context context, TouchController touchListener, int[] boardColors,GameBoardMatrix matrix) {
		super(context);
		this.boardColors = boardColors;
		bitmapImage = createChessBoard();

		setImageBitmap(bitmapImage);
		touchListener.setBitmap(bitmapImage);

		setScaleType(ScaleType.FIT_START);
		setOnTouchListener(touchListener);
		
		squares=new UISquares();
		
		Drawing dp=new Drawing(bitmapImage,getContext());
		dp.drawPieces(matrix, squares.getSquares());
		setImageBitmap(bitmapImage);
	}

	/**
	 * Creaza o lista cu culori pentru imaginea ce va fi afisata.
	 * */
	private int[] createColors() {
		int[] colors = new int[Utils.BOARD_WIDTH * Utils.BOARD_HEIGHT];

		int squareSizeX = Utils.BOARD_WIDTH / Utils.BOARD_SIZE;
		int squareSizeY = Utils.BOARD_HEIGHT / Utils.BOARD_SIZE;

		int color = boardColors[0];
		int colorIndex = 0;
		int checkChangeColorOnLine = 1;
		int checkChangeColorOnColumn = 1;

		for (int k = 0; k < Utils.BOARD_HEIGHT; k++) {
			checkChangeColorOnLine = 1;
			for (int i = 0; i < Utils.BOARD_WIDTH; i++) {

				if (i == checkChangeColorOnLine * squareSizeX) {
					color = changeColor(color);
					checkChangeColorOnLine++;
				}
				colors[colorIndex++] = color;
			}

			if (k == checkChangeColorOnColumn * squareSizeY) {
				color = changeColor(color);
				checkChangeColorOnColumn++;
			}
		}

		return colors;
	}

	/**
	 * * Inverseaza culoarea, daca color e alb se schimba in negru si invers.
	 * 
	 * @param color
	 *            - culoare ce se va schimba
	 * @return culoarea inversata.
	 */
	private int changeColor(int color) {
		if (color == boardColors[0]) {
			color = boardColors[1];
		} else {
			color = boardColors[0];
		}
		return color;
	}

	/**
	 * Creaza un bitmap a tablei de sah
	 * */
	private Bitmap createChessBoard() {

		Bitmap bitmap = null;
		int[] colors = createColors();
		Config config = Config.ARGB_4444;

		bitmap = Bitmap.createBitmap(Utils.BOARD_WIDTH,
				Utils.BOARD_HEIGHT, config);
		// .createBitmap(colors, DataUtil.WIDTH, DataUtil.HEIGHT, c);

		bitmap.setPixels(colors, 0, Utils.BOARD_WIDTH, 0, 0,
				Utils.BOARD_WIDTH, Utils.BOARD_HEIGHT);

		return bitmap;
	}

}
